package com.example.asynctaskdemo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.widget.ListView;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class MainActivity extends Activity {
	private ListView mListView;
	private LessonsAdapter adapter;
	private List<LessonBean> datas;
	private static String url = "http://www.imooc.com/api/teacher?type=4&num=30";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        new NewsAsyncTask().execute(url);
    }


    private void initView() {
		mListView = (ListView) findViewById(R.id.my_listview);
		
	}

	class NewsAsyncTask extends AsyncTask<String, Void, List<LessonBean>> {
		
		

		@Override
		protected List<LessonBean> doInBackground(String... arg0) {
			
			return getData(arg0[0]);
		}
		@Override
		protected void onPostExecute(List<LessonBean> result) {
			
			super.onPostExecute(result);
			adapter = new LessonsAdapter(MainActivity.this, datas);
			mListView.setAdapter(adapter);
		}
		
	}

	/**
	 * 
	 * @param url
	 * @return
	 */
	public List<LessonBean> getData(String url) {
//		List<LessonBean> datas = new ArrayList<LessonBean>();
		try {
			String json = readStream(new URL(url).openStream());
			JSONObject jsonObject = JSONObject.parseObject(json);
			datas = jsonObject.parseArray(jsonObject.getJSONArray("data").toJSONString(), LessonBean.class);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return datas;
	}
	
	private String readStream(InputStream is) {
		InputStreamReader isr;
		String result = "";
		try {
			String line;
			isr = new InputStreamReader(is,"utf-8");
			BufferedReader br = new BufferedReader(isr);
			try {
				while ((line = br.readLine()) != null) {
					result += line;
					
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
		
	}
    
}
